package com.one.blocks.rbac.controller.valid;

import com.one.blocks.rbac.domain.SysRole;
import com.one.blocks.rbac.manager.SysRoleManager;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author linfuxin Created on 2022-08-16 17:41:36
 */
public class RoleTypeValidator implements ConstraintValidator<RoleType, Integer> {

    @Autowired
    private SysRoleManager sysRoleManager;

    private RoleType constraintAnnotation;

    @Override
    public void initialize(RoleType constraintAnnotation) {
        this.constraintAnnotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("不能为null").addConstraintViolation();
            return false;
        }
        SysRole data = sysRoleManager.get(value);
        if (data == null) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("不存在的记录").addConstraintViolation();
            return false;
        }
        for (int type : constraintAnnotation.value()) {
            if (data.getType().equals(type)) {
                return true;
            }
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("不合法的角色类型").addConstraintViolation();
        return false;
    }
}
